package com.api.sw.duban.impl;

import com.alibaba.fastjson.JSONObject;
import com.api.sw.duban.baseinter.Execute;
import com.api.sw.duban.util.CacheUtil;
import com.api.sw.duban.util.LogTool;
import weaver.general.Util;

import java.lang.reflect.Method;

public class ExecuteImpl implements Execute {
    private final static LogTool log = new LogTool("/log/duban/",false);
    private String pid="";
    private String  mothed="";
    private JSONObject param=null;
    public ExecuteImpl(String pid,String mothed,JSONObject param){
        this.pid=pid;
        this.mothed=Util.null2String(mothed).trim() ;
        this.param=param;
    }
    @Override
    public Object Execute() throws Exception {
        Object obj=null;
        if("".equals(Util.null2String(pid).trim())||"".equals(Util.null2String(mothed).trim())){
            return null;
        }
        log.writeLog("Execute pid--->"+pid+" mothed---->"+mothed);
        try{
            String classMothed="";
            String classname="";
            if(mothed.lastIndexOf(".")>0){
                classMothed=this.mothed.substring(mothed.lastIndexOf(".")+1);
                classname=this.mothed.substring(0,mothed.lastIndexOf("."));
            }else{
                log.writeLog("Execute pid--->"+pid+" mothed---->"+mothed+" ");
            }
            if("".equals(classname)||"".equals(classMothed)){
                CacheUtil.getInstance().removeExecute(pid);
                return null;
            }
            Class clazz=Class.forName(classname);
            if(clazz!=null){
                Method Method=clazz.getDeclaredMethod(classMothed,JSONObject.class);
                Object newOj=clazz.newInstance();
                if(newOj!=null){
                    obj=Method.invoke(newOj,this.param);
                }else{
                    log.writeLog("Execute Exception-->无法初始化对象");
                }

            }else{
                log.writeLog("Execute Exception-->无法加载对象");
            }
            CacheUtil.getInstance().removeExecute(pid);
        }catch(Exception e){
            CacheUtil.getInstance().removeExecute(pid);
            log.writeLog("Execute Exception-->"+e.getMessage());
        }
        return obj;
    }
}
